import { fetchAuthorList, addAuthor, updateAuthor, deleteAuthor, changeAuthorStatus } from '../services/contentService';
import { decryptRes, dealPagination } from '../utils/requestUtil';
import { message } from 'antd';

export default {
  namespace: 'author',

  state: {
    authorList: [],
    pagination: { current: 1, pageSize: 10 },
  },

  effects: {
    *fetchAuthorList({ payload }, { call, put }) {
      const response = JSON.parse(decryptRes(yield call(fetchAuthorList, payload)));
      console.log('接口返回数据：', response);
      if (response.code === 0) {
        let data = response.data;
        yield put({
          type: 'authorListReducer',
          payload: { data },
        });
      } else {
        message.error('调用服务器出错!' + response.msg);
      }
    },

    *addAuthor({ payload, callback }, { call, put }) {
      console.log('前端参数', payload)
      const response = JSON.parse(decryptRes(yield call(addAuthor, payload)));
      console.log('接口返回数据：', response);

      if (response.code === 0) {
        message.success('添加成功！');
        if (callback) callback();
      } else {
        message.error('调用服务器出错!' + response.msg);
      }
    },

    *updateAuthor({ payload, callback }, { call, put }) {
      console.log('前端参数', payload)
      const response = JSON.parse(decryptRes(yield call(updateAuthor, payload)));
      console.log('接口返回数据：', response);

      if (response.code === 0) {
        message.success('保存成功！');
        if (callback) callback();
      } else {
        message.error('调用服务器出错!' + response.msg);
      }
    },

    *deleteAuthor({ payload, callback }, { call, put }) {
      console.log('前端参数', payload)
      const response = JSON.parse(decryptRes(yield call(deleteAuthor, payload)));
      console.log('接口返回数据：', response);

      if (response.code === 0) {
        message.success('删除成功！');
        if (callback) callback();
      } else {
        message.error('调用服务器出错!' + response.msg);
      }
    },

    *changeAuthorStatus({ payload, callback }, { call, put }) {
      console.log('前端参数', payload)
      const response = JSON.parse(decryptRes(yield call(changeAuthorStatus, payload)));
      console.log('接口返回数据：', response);

      if (response.code === 0) {
        message.success('操作成功！');
        if (callback) callback();
      } else {
        message.error('调用服务器出错!' + response.msg);
      }
    },

  },





  reducers: {
    authorListReducer(state, action) {
      return {
        ...state,
        authorList: action.payload.data.dataList,
        pagination: dealPagination(action.payload.data.pageInfo),
      };
    },
  },
};
